import $ from 'jquery'

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes[0]) {
            if ($(mutation.addedNodes[0]).find(".ld-input").length !== 0) { // 监听元素的创建
                const inputs = mutation.addedNodes[0].querySelectorAll("input")
                console.log(inputs);
                for (let i = 0; i < inputs.length; i++) {
                    renderInput($(inputs[i]).attr("type"), $(inputs[i]), $(inputs[i]).val(), $(inputs[i]).attr("placeholder"), $(inputs[i]).attr("width"), $(inputs[i]).attr("height"), $(inputs[i]).attr("readonly"), $(inputs[i]).attr("clearable"))
                }
            }
        }
    });
});

observer.observe(window.document, {
    subtree: true,
    childList: true,
    attributes: true,
    attributeFilter: ['src', 'href', 'action']
});

$(".ld-input").each(function () {
    let type = $(this).attr("type"),
        el = $(this),
        value = $(this).val(),
        placeholder = $(this).attr("placeholder"),
        width = $(this).attr("width") || '180px',
        height = $(this).attr("height") || '40px',
        readonly = $(this).attr("readonly"),
        clearable = $(this).attr("clearable")
    renderInput(type, el, value, placeholder, width, height, readonly, clearable)
})

function renderInput(type, el, value, placeholder, width, height, readonly, clearable) {
    if (readonly === false || readonly === undefined || readonly === "")
        readonly = ""
    let str = ""
    str = `<div class="ld-input-group" style="width:${width};height:${height};">
                <input type="${type}" class="ld-input-inner" placeholder=${placeholder} value="${value}" ${readonly}>
            </div>`
    if (clearable === "") {
        str = `<div class="ld-input-group" style="width:${width};height:${height};">
                    <input type="${type}" class="ld-input-inner ld-input-inner-close" placeholder=${placeholder} value="${value}" ${readonly}>
                    <i class="close iconfont icon-cuowu"></i>
                </div>`
    }


    if (type === "textarea") {
        str = `<div class="ld-input-group" style="width:${width};height:${height};">
                <textarea type="${type}" class="ld-textarea-inner" placeholder=${placeholder} value="${value}" ${readonly}></textarea>
            </div>`
    }
    el.after(str)
    el.remove()
}
$("body").on("input", ".ld-input-inner-close", function () {
    if ($(this).val() === "")
        $(this).siblings("i.close").hide()
    else
        $(this).siblings("i.close").show()
})

$("body").on("click", ".ld-input-group i.close", function () {
    $(this).siblings(".ld-input-inner").val("")
    $(this).hide()
    if (typeof clearLdInput === "function")
        clearLdInput()

})